package com.example.testlxr9096;// ThreadPoolManager.java


import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ThreadPoolManager {
    private static ThreadPoolManager instance;
    private final ScheduledExecutorService scheduledExecutor;
    private Future<?> periodicTaskFuture;

    private ThreadPoolManager() {
        scheduledExecutor = Executors.newScheduledThreadPool(5);
    }

    public static synchronized ThreadPoolManager getInstance() {
        if (instance == null) {
            instance = new ThreadPoolManager();
        }
        return instance;
    }

    /**
     * 启动500ms周期性任务
     */
    public void start500msTask(Runnable task) {
        if (periodicTaskFuture == null || periodicTaskFuture.isCancelled()) {
            periodicTaskFuture = scheduledExecutor.scheduleAtFixedRate(
                    task, 0, 500, TimeUnit.MILLISECONDS
            );
        }
    }

    /**
     * 停止500ms周期性任务
     */
    public void stop500msTask() {
        if (periodicTaskFuture != null && !periodicTaskFuture.isCancelled()) {
            periodicTaskFuture.cancel(true);
            periodicTaskFuture = null;
        }
    }

    /**
     * 检查周期性任务是否在运行
     */
    public boolean isPeriodicTaskRunning() {
        return periodicTaskFuture != null && !periodicTaskFuture.isCancelled();
    }

    /**
     * 执行一次性任务
     */
    public void executeOneTimeTask(Runnable task) {
        scheduledExecutor.execute(task);
    }

    /**
     * 关闭线程池
     */
    public void shutdown() {
        stop500msTask();
        scheduledExecutor.shutdown();
    }
}